<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true">
      <el-form-item label="用户账号" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户账号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="openSelectUser"
          v-hasPermi="['web:base:system:role:add']"
        >
          添加用户
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="CircleClose"
          :disabled="multiple"
          @click="cancelAuthUserAll"
          v-hasPermi="['web:base:system:role:remove']"
        >
          批量取消授权
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户账号" prop="userName" />
      <el-table-column label="用户姓名" prop="nickName" />
      <el-table-column label="邮箱" prop="email" />
      <el-table-column label="手机" prop="phonenumber" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="CircleClose"
            @click="cancelAuthUser(scope.row)"
            v-hasPermi="['web:base:system:role:remove']"
          >
            取消授权
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <select-user ref="selectRef" :roleId="queryParams.roleId" @ok="handleQuery" />
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref } from 'vue';
  import { useRoute } from 'vue-router';
  import { allocatedUserList, authUserCancel, authUserCancelAll } from '@/api/system/role';
  import { useDict } from '@/utils/dict';
  import modal from '@/plugins/modal';
  import selectUser from './selectUser';

  const { proxy } = getCurrentInstance();

  const route = useRoute();
  const { sys_normal_disable } = useDict('sys_normal_disable');

  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    roleId: route.params.roleId,
    userName: undefined,
    phonenumber: undefined,
  });
  const queryRef = ref(null);
  const userList = ref([]);
  const loading = ref(true);
  const showSearch = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const userIds = ref([]);
  const selectRef = ref(null);

  function getList() {
    loading.value = true;
    allocatedUserList(queryParams.value, {
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize,
    })
      .then((res) => {
        userList.value = res?.data?.records ?? [];
        total.value = res?.data?.total ?? 0;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  function handleClose() {
    const obj = { path: '/system/role' };
    proxy.$tab.closeOpenPage(obj);
  }

  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  function resetQuery() {
    queryRef.value?.resetFields();
    handleQuery();
  }

  function handleSelectionChange(selection) {
    userIds.value = selection.map((item) => item.userId);
    multiple.value = !selection.length;
  }

  function openSelectUser() {
    selectRef.value.show();
  }

  function cancelAuthUser(row) {
    modal
      .confirm('确认要取消该用户"' + row.userName + '"角色吗？')
      .then(function () {
        return authUserCancel({ userId: row.userId, roleId: queryParams.value.roleId });
      })
      .then(() => {
        getList();
        modal.msgSuccess('取消授权成功');
      })
      .catch(() => {});
  }

  function cancelAuthUserAll() {
    const roleId = queryParams.value.roleId;
    const uIds = userIds.value.join(',');
    modal
      .confirm('是否取消选中用户授权数据项?')
      .then(function () {
        return authUserCancelAll({ roleId: roleId, userIds: uIds });
      })
      .then(() => {
        getList();
        modal.msgSuccess('取消授权成功');
      })
      .catch(() => {});
  }

  getList();
</script>
